package com.tbsoft.ehr.login;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.tbsoft.ehr.model.BaseEntity;
/**
 * @desc 用户信息
 * @author vastdream
 *
 */
@Entity
@Table(name="EHR_USER")
public class UserInfo extends BaseEntity{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String userId;
	private String userName;
	private String password;
	private String authPassword;
	@Transient
	public String getAuthPassword() {
		return authPassword;
	}

	public void setAuthPassword(String authPassword) {
		this.authPassword = authPassword;
	}

	@Column(name="USER_NAME",length=50)
	public String getUserName() {
		return userName;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
	@Column(name="USER_PASSWORD",length=41)
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Id
	@Column(name="USER_ID",length=16)
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	
	private Set<RoleInfo> roleSet = new HashSet<RoleInfo>();
	
	private Set<MenuInfo> menuSet;
	@ManyToMany(targetEntity=RoleInfo.class,fetch=FetchType.EAGER,cascade={CascadeType.MERGE})
	@JoinTable(name="EHR_USER_ROLE",
		joinColumns={@JoinColumn(referencedColumnName="USER_ID")},
		inverseJoinColumns={@JoinColumn(referencedColumnName="ROLE_ID")}
	)
	public Set<RoleInfo> getRoleSet() {
		return roleSet;
	}
	
	public void setRoleSet(Set<RoleInfo> roleSet) {
		this.roleSet = roleSet;
	}
	@Transient
	public Set<MenuInfo> getMenuSet() {
		return menuSet;
	}
	@Transient
	public synchronized List<MenuInfo> getMenuList(){
		List<MenuInfo> tmpList = new ArrayList<MenuInfo>();
		if(roleSet.size()>0){
			tmpList.addAll(menuSet);
		}
		Collections.sort(tmpList, new Comparator<MenuInfo>(){

			@Override
			public int compare(MenuInfo o1, MenuInfo o2) {
				return o1.getMenuId().compareTo(o2.getMenuId());
			}}   );
		return tmpList;
	}

	public void setMenuSet(Set<MenuInfo> menuSet) {
		this.menuSet = menuSet;
	}
	@Override
	public String toString() {
		return userId+":"+userName;
	}
	@Override
	public int hashCode() {
		return (""+userId).hashCode();
	}
@Override
public boolean equals(Object obj) {
	if(obj instanceof UserInfo)
		return ((UserInfo)obj).getUserId().equals(userId);
	else
	return false;
}
}
